import pymysql
from utils import ERROR
from typing import List

class MySQL():
    def __init__(self, host = "92.168.118.129", port = 3306, user = "root", password = "123456", database = "cbgpt"):
        try:
            self.db = pymysql.connect(
                host = '192.168.118.129',   #服务端地址
                port = 3306,    #服务端端口
                user = 'root',   #用户名		
                password = '123456',   #密码
                database = 'cbgpt',   #要连接的数据库
            )
            self.cursor = self.db.cursor(pymysql.cursors.DictCursor)
        except Exception as e:
            ERROR(e)
    
    def select(self, sql, param) -> List:
        selectResult = self.cursor.execute(sql, param)       
        return selectResult, self.cursor.fetchall()
        
    def insert(self ,sql, param) -> List:
        insertResult = self.cursor.execute(sql, param)
        insertId = self.cursor.lastrowid
        self.db.commit()
        return insertId

    # excutemany并不能获取全部的插入数据的自增id
    def insertMany(self, sql, params) -> List:
        ids= []
        for param in params:  
            self.cursor.execute(sql, param)
            ids.append(self.cursor.lastrowid)
        self.db.commit()
        print(self.cursor)
        return ids
    

    def close(self):
        self.cursor.close()
        self.db.close()
        
